package com.flong.selenium;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;

import com.flong.common.IoUtil;

@SuppressWarnings("all")
public class MeiTuanTest1 {

	public static WebDriver driver;

	static {
		System.setProperty("webdriver.ie.driver", "d:/Devsoft/IEDriverServer.exe");
		// driver = new ChromeDriver();
		DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
		ieCapabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
		ieCapabilities.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR,UnexpectedAlertBehaviour.ACCEPT);
		driver = new InternetExplorerDriver(ieCapabilities); // 问题3解决方法
		driver.manage().timeouts().implicitlyWait(1000, TimeUnit.SECONDS);// SECONDS是秒的意思
	}

	public static void main(String[] args) throws IOException, Exception {	
		
		String resultText="";
		for(int k=1; k<=38;k++){
			
			String  url = "";
			if(k==1){
				url ="http://wh.meituan.com/s/?w="+URLEncoder.encode("足疗");
			}else{
				url ="http://wh.meituan.com/s/"+URLEncoder.encode("足疗")+"/all/all/page"+k+"?w="
					+URLEncoder.encode("足疗");
			}

			driver.navigate().to(url);
			if(isAlertPresent()){
				driver.switchTo().alert().accept();
			}
			driver.manage().window().maximize();
			Thread.sleep(1800);
			JavascriptExecutor js = (JavascriptExecutor)driver;
			js.executeScript("scrollTo(0,10000)");//向下拉到底
			js.executeScript("window.scrollBy(0,3500)");
			Thread.sleep(2800);
			WebElement html = driver.findElement(By.cssSelector("html[class='yui3-js-enabled']"));
			WebElement content = html.findElement(By.id("content"));
			
			List<WebElement> dealList = content.findElements(By.xpath("//div[@data-component='deal-list']"));
			String resultUrl ="";
			for(WebElement deal:dealList){
				List<WebElement> ables = deal.findElements(By.xpath("//div/h3//a"));
				for(WebElement a:ables){
					String attribute = a.getAttribute("href");
					resultUrl+=attribute+"\n";
					
				}
			}
			resultText+= resultUrl+"\n";
		}
		IoUtil.save("d:/pc_task/wh_zl_url.txt", resultText);
		System.out.println("success");
		driver.close();
		driver.quit();
	}

	protected static boolean isAlertPresent() {
        try {
          driver.switchTo().alert();
          return true;
        } catch (NoAlertPresentException e) {
          return false;
        }
      }
}